package com.hnevc.nbastar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class NBAStarListActivity extends AppCompatActivity {

    List<NBAStarItem> itemList = new ArrayList<>();
    private RecyclerView.Adapter adapter;
    private RecyclerView rvList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nba_star_list);
        // 1、初始化对象
        rvList = findViewById(R.id.rv_list);
        // 2、设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        rvList.setLayoutManager(layoutManager);
        // 3、获取数据
        itemList = getData();

    }

    /**
     * 请求网络获取列表数据
     *
     * @return list
     */
    private List<NBAStarItem> getData() {
        final String url = "http://littlecurl.imwork.net/star/list";

        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();

                try (Response response = client.newCall(request).execute()) {
                    String jsonStr = response.body().string();
                    JSONObject jsonObject = JSON.parseObject(jsonStr);
                    String data = jsonObject.get("data").toString();
                    // 把 Json 格式的 字符串 解析成 Java List
                    itemList = JSON.parseArray(data, NBAStarItem.class);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 4、将数据设置给适配器
                            adapter = new NBAStarItemAdapter(NBAStarListActivity.this, itemList);
                            // 5、将适配器设置给 RecyclerView
                            rvList.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
                        }
                    });
                } catch (IOException e) {
                        e.printStackTrace();
                }

            }
        }).start();

        return itemList;
    }
}
